package com.zlsy.secondtime.jmm;

/**
 * @author zhouliang
 * @date 2020/6/4 8:30
 * 演示可见性带来的问题
 */
public class FieldVisibility {
    int a = 1;
    int b = 2;

    private void change() {
        a = 3;
        b = a;
    }

    private void print() {
        System.out.println("b = " + b + ";a = " + a);
    }


    public static void main(String[] args) {
        while (true) {
            //为什么把这个对象放在外面线程打印b和a就不出现乱的？
            // 解答：只有一个fieldVisibility对象，而我是每次新建一个fieldVisibility对象，所以每次都是初始值1和2，但是你的对象一直是3不变了。
            FieldVisibility fieldVisibility = new FieldVisibility();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    fieldVisibility.change();
                }
            }).start();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    fieldVisibility.print();
                }
            }).start();
        }
    }

}
